package com.hddf.project.base;

import org.hibernate.Session;
import org.kommii.mysql_conn_pool.SessionProvider;

import com.hddf.project.util.O;

public class BaseService {

	private static BaseDaoImpl bdi = null;
	private static BaseService bs = null;

	static {
		if (null == bdi) {
			bdi = new BaseDaoImpl();
		}
		if (null == bs) {
			bs = new BaseService();
		}
	}

	public static BaseService getInService() {
		return bs;
	}

	/**
	 * 添加
	 * 
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public boolean addObject(Object obj) {
		Session s = null;
		try {
			s = SessionProvider.getSession();
			bdi.add(obj, s);
			SessionProvider.commitSession(s);
			return true;
		} catch (Exception e) {
			SessionProvider.rollback(s);
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 根据ID获取实体
	 */
	@SuppressWarnings("rawtypes")
	public Object getObjectById(int id, Class clazz) {
		Session s = null;
		try {
			s = SessionProvider.getSession();
			Object obj = bdi.get(clazz, id, s);
			SessionProvider.commitSession(s);
			return obj;
		} catch (Exception e) {
			SessionProvider.rollback(s);
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 删除
	 * 
	 * @param
	 * @return
	 */
	public boolean deleteObject(Object object) {
		Session s = null;
		try {
			s = SessionProvider.getSession();
			bdi.delete(object, s);
			SessionProvider.commitSession(s);
			return true;
		} catch (Exception e) {
			SessionProvider.rollback(s);
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 删除
	 * 
	 * @param
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public boolean deleteObject(int id, Class clazz) throws Exception {
		Object object = this.getObjectById(id, clazz);
		if (null != object) {
			this.deleteObject(object);
			return true;
		}
		return false;
	}

	/**
	 * 修改
	 * 
	 * @param
	 * @return
	 */
	public boolean updateObject(Object object) {
		Session s = null;
		try {
			s = SessionProvider.getSession();
			bdi.update(object, s);
			SessionProvider.commitSession(s);
			return true;
		} catch (Exception e) {
			SessionProvider.rollback(s);
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 将字符串转化成数组
	 * 
	 * @param values
	 * @return
	 */
	public int[] getIntValue(String values) {
		int[] endValue = null;
		String[] nextValue = null;
		if (O.ckSt(values)) {
			if (-1 != values.indexOf(",")) {
				nextValue = values.split(",");
				endValue = new int[nextValue.length];
				for (int i = 0; i < nextValue.length; i++) {
					endValue[i] = Integer.valueOf(nextValue[i]);
				}
			} else {
				endValue = new int[1];
				endValue[0] = Integer.valueOf(values);
			}
		}
		return endValue;
	}
}